JS async functions

revision:


In JavaScript, asynchronous functions are important because of its single threaded nature.

This means that the next line of code cannot run until the current one has finished; the next function cannot run until the current one has completed.

With the help of asynchronous functions, JavaScript's event loop can take care of other things when the function is requesting some other resource. Blocks of code run in parallel when it comes to asynchronous; asynchronous functions run independently.

An asynchronous function is implemented using async, await and promises.

Syntax : async function name([param[, param[, ...param]]]) { statements}

async: the "async" keyword defines an asynchronous function.

await: the "async" function contains "await" that pauses the execution of "async" function. "await" is only valid inside the "async" function.

promise: a promise is a proxy value. It tells us about the success/failure of the asynchronous event. A Promise must contain resolve() or reject() call or else the consumer of the Promise will never know whether Promise is fulfilled or not. If that happened then the program will keep waiting for await and that code block will never be executed further.

Examples

examples: asynchronous function

code:
                    <script>
                        var msg = document.getElementById("message");
                        function f1() {
                            return new Promise(function (resolve, reject) {
                                setTimeout(function () {
                                msg.innerHTML += "<span>f1 is starting</span><br>";
                                msg.innerHTML += "<span>f1 is ending</span><br>";
                                    resolve();
                                }, 100);
                            })
                        }
                        async function f2() {
                            msg.innerHTML += "<span>f2 is starting</span><br>";
                            // Engine waits for f1() to finish it's execution before executing the next line                                
                            await f1(); 
                            msg.innerHTML += "<span>f2 is ending</span><br>";
                        }

                        f2();

                        // (A) asynchronous add
                        async function add (first, second) {
                        return first + second;
                        }
                        // (B) run!
                            var result = add(2, 3);
                        document.getElementById("async01").innerHTML = result; // promise
                        // (C) here is how to work with promises
                        result
                        // (C1) resolve result
                            .then(res => {
                            document.getElementById("async01A").innerHTML = res; // 5
                            })
                            // (C2) optional - catch error
                            .catch(err => {
                                document.getElementById("async0B").innerHTML =err;
                            })
                            
                            // (C3) optional - finally
                            .finally(() => {
                                document.getElementById("async01C").innerHTML = "Finally";
                        });
                    </script>
                

examples: async runs in parallel

code:
                    <script>

                        //async runs in parallel
                        async function add (first, second) {
                            return first + second;
                        }
                        async function multiply (first, second) {
                        return first * second;
                        }
                        add(2, 3).then(result => {document.getElementById("async02").innerHTML = result;}); 
                        multiply(5, 5).then(result => { document.getElementById("async02A").innerHTML = result; });

                    // async chain
                        async function add_1 (first, second) {
                            return first + second;
                        }
                        async function multiply_1 (first, second) {
                            return first * second;
                        }
                        // (B) run!
                        // (B1) empty holder
                        var result1 = null;
                        
                        // (B2) async chain
                        add_1(2, 3).then(res => {
                            multiply_1(res, 5).then(res => {
                                result1 = res;
                                document.getElementById("async02B").innerHTML = result1;
                            });
                        });
                    </script>    
                

examples: await; waits for the result from an asynchronous function, but "await" can only be used inside another async function.

wait 3 seconds (3000 milliseconds) for this page to change.

code:
                    <script>
                        async function myDisplay() {
                            let myPromise = new Promise(function(myResolve, myReject) {
                                setTimeout(function() { 
                                    myResolve("It's worth it !!"); }, 3000);
                            });
                            document.getElementById("async02").innerHTML = await myPromise;                        
                        }
                        myDisplay();

                        async function add (first, second) {
                            return first + second;
                        }
                        async function multiply (first, second) {
                            return first * second;
                        }
                        async function calc () {
                            var result = await add(2, 3);
                            document.getElementById("async03A").innerHTML = result; // 5
                            result = await multiply(result, 5);
                            document.getElementById("async03B").innerHTML =result; // 25
                        }
                        calc();
                    </script>